package com.example.aigc_education.common;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.aigc_education.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 公共字段自动填充
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final Long DEFAULT_USER_ID = 1L;

    /**
     * 插入时填充
     * @param metaObject 元数据对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]...");
        log.info(metaObject.toString());
//        metaObject.setValue("createTime", LocalDateTime.now());
//        metaObject.setValue("updateTime", LocalDateTime.now());
//        metaObject.setValue("createBy", SecurityUtils.getLoginUser().getUser().getUserName());
//        metaObject.setValue("updateBy", SecurityUtils.getLoginUser().getUser().getUserName());
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            userId = DEFAULT_USER_ID;
        }
        this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("createBy", userId, metaObject);
        this.setFieldValByName("updateBy", userId, metaObject);
    }

    /**
     * 更新时填充
     * @param metaObject 元数据对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]...");
        log.info(metaObject.toString());

        long id = Thread.currentThread().getId();
        log.info("线程id为：{}", id);

        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            userId = DEFAULT_USER_ID;
        }
//
//        metaObject.setValue("updateTime", LocalDateTime.now());
//        metaObject.setValue("updateBy", SecurityUtils.getLoginUser().getUser().getUserName());
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateBy", userId, metaObject);
    }
}
